require 'View/UIBase/UIBase'

UIGiftVipDetail = UIBase.New(PanelResNames.UIGiftVipDetail)

function UIGiftVipDetail.Init(func, id)
    UIGiftVipDetail.activeId = id
    UIBase.Init(UIGiftVipDetail, func);
end

function UIGiftVipDetail:OnCreate()
    self.vipTipsTitle = self:GetChild("vipBg"):GetChild("title");
    self.vipTipsTitleRewardList = self:GetChild("listReward");
    --self.vipTipsPrivilegeTitle = self:GetChild("titleVipPrivilege");
    self.vipTipsPrivilegeList = self:GetChild("listInfo");
    --self.vipTipsVipRight = self:GetChild("vipRight");
    --self.vipTipsVipLeft = self:GetChild("vipLeft");
   -- self.titleInfo = self:GetChild("titleInfo");
   -- self.titleInfo.text = getLanguage("VipTips003")
    self.buttomBug = self:GetChild("buttomBug")
    --self.buttomBug.title = getLanguage("button_01");
    self.buyIcon = self.buttomBug:GetChild("icon");
    self.buyNum = self.buttomBug:GetChild("title");
    self.buyState = self.buttomBug:GetController("state");
    self.rewardPrivilege = self:GetController("reward");
    self.vipLevel = self:GetChild("VipLevel");
    self.vipNumList = self:SetDynamicList(self:GetChild("VipNumList"),self.refreshVipNumListItem, self, true)


    self.vipIcon = self:GetChild("vipIcon")
    self.vipProgress = self:GetChild("exp")
    self.vipProgressNum =  self:GetChild("num");
    self.vipTips = self:GetChild("vipTips")
    self.isVipMaxController = self:GetController("isVipMax");

    -- 帮助按钮
    self.helpVip = self:GetChild("helpVip")

    self:RegisterOnClick(self.buttomBug,self.ClickReceiveVipReward);
    --self:RegisterOnClick(self.vipTipsVipRight,self.ClickVipRight);
    --self:RegisterOnClick(self.vipTipsVipLeft,self.ClickVipLeft);
    self.isGetReward = false;
    self:RegisterOnClick(self:GetChild("back"),self.OnClose);
    --self:RegisterTouchBegin(self.vipTipsPrivilegeList, self.DragStart)
    --self:RegisterTouchEnd(self.vipTipsPrivilegeList, self.DragEnd)

    if self.fguiObj then
        self.fguiObj.onTouchBegin:Add(self.OnTouchView, self)
    end
end

-- 显示
function UIGiftVipDetail:OnEnable()
   -- local nowLv, progress, limit, nextLv, rewardLv = logicMgr.VipManager.GetVipInfo();
    --if rewardLv ~= nil then
     --   self.nowVipLv = math.max(1, rewardLv);
   -- else
      --  self.nowVipLv = math.max(1, nowLv);
    --end
   -- self:updateVipItem();
    self:refreshView();
    self.vipNumList.onClickItem:Add(self.ClickVipNumTag, self);
    self:refreshVipLevel();
end

function UIGiftVipDetail:refreshVipLevel()
    --local severData, itemData, modelTableData = logicMgr.CostManager.getCostData(self.activeId);
    local nowLv, progress, limit, nextLv = logicMgr.VipManager.GetVipInfo();
    local vipExp = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.VipExp);
    if nextLv == nil then
        self.isVipMaxController.selectedIndex = 1;
        self.vipProgress.value = 100;
        self.vipProgressNum.text = progress.."/"..limit;
        self.vipTips.text = getLanguage("Viptext1002");
    else
        self.vipProgressNum.text = progress.."/"..limit;
        self.vipProgress.value = progress / limit * 100;
        self.vipTips.text = string.format(getLanguage("Viptext1001"), limit - progress, nextLv)
        --local modelTableData;
        --local curData = logicMgr.CostManager.getCostTableDataById(self.activeId);
        --if curData ~= nil then
        --    modelTableData = G.dataTable[curData.f_ModelName][tostring(self.activeId)];
        --else
        --    logError("找不到集市t_storeentrance f_StoreId:"..tostring(self.activeId));
        --end
        --if modelTableData ~= nil then
        --    self.vipTips.text = string.format(getLanguage(modelTableData.f_VipTip,nil,"获得%d到达%d级光耀圣使"), limit - progress, nextLv)
        --else
        --    logError("找不到集市模板"..tostring(curData.f_ModelName).." f_StoreId:"..tostring(self.activeId));
        --    self.vipTips.text = "";
        --end
        if vipExp ~= nil then
           self.vipIcon.url = EnumConst.AtlasPath.ItemAtlas..vipExp["icon"];
        end
        self.isVipMaxController.selectedIndex = 0;
    end
end

function UIGiftVipDetail:refreshView()
    if self.nowVipLv ~= nil and self.nowVipLv > 0 and self.vipNumContent ~= nil then
        self.vipNumContent[self.nowVipLv].selectedIndex = 0;
    end
    local nowLv, progress, limit, nextLv, rewardLv = logicMgr.VipManager.GetVipInfo();
    if rewardLv ~= nil then
        self.nowVipLv = math.max(1, rewardLv);
    else
        self.nowVipLv = math.max(1, nowLv);
    end
    self.curVipLv = logicMgr.VipManager.getVipLevel();
    self:updateVipItem();
    --if self.vipNumContent == nil then
        self.vipNumContent = {};
        self.vipItemMaxNum = logicMgr.VipManager.GetVipTableNum();
        self.vipNumList.numItems = self.vipItemMaxNum + 4;
        -- self.vipNumList:ScrollToView(self.nowVipLv + 2);
       -- self.vipNumContent[self.nowVipLv].selectedIndex = 1;
    --else
        --self:MoveVipNumList(self.nowVipLv + 1, false);
    --end
    self:MoveVipNumList(self.nowVipLv + 1, false);
    --self.vipNumContent[self.nowVipLv].selectedIndex = 1;
    self.isGetReward = false;
end

function UIGiftVipDetail:updateVipItem()
    local data, isReward = logicMgr.VipManager.GetVipTableDataByLv(self.nowVipLv);
    self.isRewarded = true;
    self.isLv = true;
    self.hasNum = true;
    if data == nil then
        --UISysTips.AddMsg("数据错误");
        return ;
    end
    local nowLv, progress, limit, nextLv, rewardLv = logicMgr.VipManager.GetVipInfo();
    self.vipLevel.text = tostring(data.f_VipLevel);
    --self.vipTipsTitle.text = string.format(getLanguage("VipTips001", nil, "%d"), data.f_VipLevel);
    self.vipTipsTitle.text = string.format(getLanguage("VipTips002", nil, "%d"), data.f_VipLevel);
    --self.vipTipsPrivilegeTitle.text = string.format(getLanguage("VipTips002", nil, "%d"), data.f_VipLevel);
    self.isRewarded = isReward;
    --if data.f_VipRewardCost ~= "" then
    --    local rewardCost = decodeJsonStrToTabel(data.f_VipRewardCost);
    --    local itemId = rewardCost[1][1];
    --    local costNum = rewardCost[1][2]
    --    local itemNum = logicMgr.ItemManager.getCurrencyCountByModelId(tonumber(itemId));
    --    local item = logicMgr.ItemManager.getItemConstDatabyModelId(itemId);
    --    self.costItemName = item.name;
    --    if item ~= nil then
    --        self.buyIcon.url = EnumConst.AtlasPath.ItemAtlas..item.icon;
    --    end
    --    if isReward then
    --        self.buyNum.text = "[color=#271B2E]" .. costNum .. "[/color]";
    --    else
    --        if itemNum >= costNum then
    --            self.buyNum.text = "[color=#271B2E]" .. costNum .. "[/color]";
    --        else
    --            self.buyNum.text = "[color=#FF2A4D]"..costNum.."[/color]";
    --            self.hasNum = false;
    --        end
    --    end
    --end
    self.buyState.selectedIndex = 0;
    if isReward == false and self.nowVipLv <= nowLv and data.f_VipReward ~= "" then
        self.rewardPrivilege.selectedIndex = 1;
        self.buyNum.text = getLanguage("VipTips007");
    else
        self.rewardPrivilege.selectedIndex = 0;
        if isReward then
            self.buyState.selectedIndex = 1;
            self.buyNum.text = getLanguage("VipTips008");
        end
        if nowLv == 0 or self.nowVipLv > nowLv then
            self.buyState.selectedIndex = 2;
            self.isLv = false;
            self.buyNum.text = getLanguage("VipTips007");
        end
    end
    if data.f_VipReward ~= "" then
        logicMgr.CostManager.RefreshItemList(self.vipTipsTitleRewardList, decodeJsonStrToTabel(data.f_VipReward), 4);
    else
        self.vipTipsTitleRewardList:RemoveChildrenToPool();
    end
    self.vipTipsPrivilegeList:RemoveChildrenToPool();
    local proBuff = {};
    local newBuff = {};
    local proFunc = {};
    local newFunc = {};
    if data.f_VipBuff ~= "" then
        if data.f_VipBuffNew ~= "" then
            local buff1 = decodeJsonStrToTabel(data.f_VipBuffNew);
            local buff2 = decodeJsonStrToTabel(data.f_VipBuff);
            for k1, v1 in pairs(buff2) do
                local isNew = false;
                for k2, v2 in pairs(buff1) do
                    if tostring(v1) == tostring(v2) then
                        isNew = true;
                        break ;
                    end
                end
                if isNew then
                    table.insert(newBuff, v1);
                else
                    table.insert(proBuff, v1);
                end
            end
        else
            proBuff = decodeJsonStrToTabel(data.f_VipBuff);
        end
    end

    if data.f_VipFuncSwitchDesc ~= "" then
        if data.f_VipFuncSwitchDescNew ~= "" then
            local func1 = decodeJsonStrToTabel(data.f_VipFuncSwitchDescNew);
            local func2 = decodeJsonStrToTabel(data.f_VipFuncSwitchDesc);
            for k1, v1 in pairs(func2) do
                local isNew = false;
                for k2, v2 in pairs(func1) do
                    if v1 == v2 then
                        isNew = true;
                        break ;
                    end
                end
                if isNew then
                    table.insert(newFunc, v1);
                else
                    table.insert(proFunc, v1);
                end
            end
        else
            proFunc = decodeJsonStrToTabel(data.f_VipFuncSwitchDesc);
        end
    end
    for k, v in pairs(newBuff) do
        self:refreshVipText(true, v, 1);
    end
    for k, v in pairs(newFunc) do
        self:refreshVipText(false, v, 1);
    end
    for k, v in pairs(proBuff) do
        self:refreshVipText(true, v, 0);
    end
    for k, v in pairs(proFunc) do
        self:refreshVipText(false, v, 0);
    end

    -- data, isReward = logicMgr.VipManager.GetVipTableDataByLv(self.nowVipLv + 1);
    -- self.vipTipsVipRight.visible = data ~= nil;
    -- data, isReward = logicMgr.VipManager.GetVipTableDataByLv(self.nowVipLv - 1);
    --self.vipTipsVipLeft.visible = data ~= nil;
end

function UIGiftVipDetail:refreshVipText(isBuff, msg, state)
    local item = self.vipTipsPrivilegeList:AddItemFromPool();
    local itemInfo = item:GetChild("info");
    local picText = item:GetChild("PicText");
    local isNew = item:GetController("IsNew");
    isNew.selectedIndex = state;
    if isBuff then
        local buff = G.dataTable["t_ecobuff"][tostring(msg)];
        if buff ~= nil then
            itemInfo.text = getLanguage(buff.f_BuffDesc);
        else
            itemInfo.text = "";
        end
    else
        if msg ~= nil and msg ~= "" then
            itemInfo.text = getLanguage(msg);
        else
            itemInfo.text = "";
        end
    end
    picText.text = getLanguage("VipTips009");
end

function UIGiftVipDetail:refreshVipNumListItem(index, obj)
    index = index - 1;
    local isTransparent = obj:GetController("IsTransparent");
    local isChoice = obj:GetController("IsChoise");
    isChoice.selectedIndex = 0;
    local num = obj:GetChild("Num");
    num.text = ""..(index - 1);
    local numChoice = obj:GetChild("NumChoice");
    numChoice.text = ""..(index - 1);
    if index < 2 or index > self.vipItemMaxNum + 1 then
        isTransparent.selectedIndex = 1;
    else
        isTransparent.selectedIndex = 0;
        UIGiftVipDetail.vipNumContent[index - 1] = isChoice;
    end
    if UIGiftVipDetail.vipItemMaxNum == (index - 1) then
        UIGiftVipDetail:MoveVipNumList(UIGiftVipDetail.nowVipLv + 1, false)
    end
end

function UIGiftVipDetail:ClickVipNumTag(context)
    local go = context.data
    local index = self.vipNumList:GetChildIndex(go);
    if index < 2 or index > self.vipItemMaxNum + 1 then
        return;
    end
    self.vipNumContent[self.nowVipLv].selectedIndex = 0;
    self.nowVipLv = index - 1
    self:updateVipItem();
    self:MoveVipNumList(index, true);
end

function UIGiftVipDetail:MoveVipNumList(index, isPlay)
    local obj = self.vipNumList:GetChildAt(index);
    local midX = self.vipNumList.scrollPane.posX + self.vipNumList.viewWidth / 2;
    local objX = obj.x + obj.width / 2;
    self.vipNumList.scrollPane.scrollStep = 1;
    if objX > midX then
        self.vipNumList.scrollPane:ScrollRight((objX - midX), isPlay);
    else
        self.vipNumList.scrollPane:ScrollLeft((midX - objX), isPlay);
    end
    self.vipNumContent[self.nowVipLv].selectedIndex = 1;
end

function UIGiftVipDetail:ClickVipRight()
    if self.nowVipLv >= self.vipItemMaxNum then
        return;
    end
    self.nowVipLv = self.nowVipLv + 1;
    self:updateVipItem();
end

function UIGiftVipDetail:ClickVipLeft()
    if self.nowVipLv <= 0 then
        return;
    end
    self.nowVipLv = self.nowVipLv - 1
    self:updateVipItem();
end

function UIGiftVipDetail:ClickReceiveVipReward()
    if self.isGetReward then
        return;
    end
    if self.isRewarded then
        UISysTips.AddMsg(getLanguage("ErrorCode_3407"));
        return;
    end
    if not self.isLv then
        UISysTips.AddMsg(getLanguage("vipTips1"));
        return;
    end
    --if not self.hasNum then
    --    UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),self.costItemName));
    --    return;
    --end
    self.isGetReward = true;
    logicMgr.VipManager.getVipDrawReward(self.nowVipLv, self.onReceiveVipRewardSuccess, self);
end

function UIGiftVipDetail:onReceiveVipRewardSuccess()
   -- self:updateVipItem();
    self:refreshView();
end

-- 关闭
function UIGiftVipDetail:DragStart(evt)
    self.lastEventX = evt.inputEvent.x;
    self.lastEventY = evt.inputEvent.y;
end

-- 关闭
function UIGiftVipDetail:DragEnd(evt)
    if math.abs(self.lastEventY - evt.inputEvent.y) < math.abs(self.lastEventX - evt.inputEvent.x) then
        if self.lastEventX - evt.inputEvent.x > 30 then
            self:ClickVipRight();
        elseif evt.inputEvent.x - self.lastEventX > 30 then
            self:ClickVipLeft();
        end
    end
end

-- 点击面板（任意区域）
function UIGiftVipDetail:OnTouchView(evt)
    if self.fguiObj == nil then
        return
    end

    local rect = {
        x = self.helpVip.x,
        y = self.helpVip.y,
        width = self.helpVip.width,
        height = self.helpVip.height
    }
    local point = self.fguiObj:GlobalToLocal(Vector2(evt.inputEvent.x, evt.inputEvent.y))
    
    -- 点击区域为按钮所在位置
    if hitTestPoint(rect, point) then
        return
    end

    self:OnHideHelpPanel()
end

-- 隐藏帮助面板
function UIGiftVipDetail:OnHideHelpPanel()
    if self.helpVip and self.helpVip.selected then
        self.helpVip.selected = false
    end
end

-- 关闭
function UIGiftVipDetail:OnClose()
    self:OnBack();
end

-- 隐藏
function UIGiftVipDetail:OnDisable()
    self.vipNumList.onClickItem:Clear();

    -- 界面关闭时隐藏帮助面板
    self:OnHideHelpPanel()
end

-- 卸载
function UIGiftVipDetail:OnDestroy()
    if self.fguiObj then
        self.fguiObj.onTouchBegin:Clear()
    end
    self.vipNumContent = nil;
end

return UIGiftVipDetail